package com.example.spring_data_jpa.repository;

import com.example.spring_data_jpa.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;

/**
 * @param null:
  * @return null
 * @author yangtongtong
 * @description 通过EntityManager拼接sql语句
 * @date 2024/9/10 15:38
 */

@Repository
public class UserHqlRepository {

    @PersistenceContext
    private EntityManager entityManager;

    public List<User> list(User user){

        StringBuilder builder = new StringBuilder();
        builder.append("from User where 1=1");
        if(!StringUtils.isEmpty(user.getName())){
            builder.append(" and name like :name");
        };
        TypedQuery<User> typedQuery = entityManager.createQuery(builder.toString(), User.class);
        if(!StringUtils.isEmpty(user.getName())){
            typedQuery.setParameter("name","%"+user.getName()+"%");
        }
        return typedQuery.getResultList();
    }

    public void save(User user){
        entityManager.persist(user);
    }


    public User findById(Integer id){
        User user = entityManager.find(User.class, id);

        return user;
    }

}
